package ${packageStr};

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.BeanUtils;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.commons.collections4.CollectionUtils;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;

<#if constant??>
import ${constant};
</#if>
import ${servicePath};
import ${voPath};
import ${addDtoPath};
import ${updateDtoPath};
<#if updateStatusDTOPath??>
imprt  ${updateStatusDTOPath}
</#if>
import ${queryDtoPath};
import ${entityPath};

@RestController
@RequestMapping("${url}")
@Api("")
public class ${controllerName}{
    @Autowired
    private ${serviceName} ${serviceNm};

    @PostMapping(value="/list/limit/{page}/{pageLimit}")
    @ApiOperation("")
    @ApiImplicitParams({
       @ApiImplicitParam(paramType = "body", name = "request", value = "",dataType=${queryDTO}),
       @ApiImplicitParam(paramType = "path", name = "page", value = "当前页数", example = "1"),
       @ApiImplicitParam(paramType = "path", name = "pageLimit", value = "每页条数", example = "1")
    })
    public ${resultClass}<IPage<${voName}>> listLimit(@RequestBody ${queryDTO} request,@PathVariable Integer page,@PathVariable Integer pageLimit) {
        ${entityName} entity = convert(request);
        IPage<${entityName}> response = ${serviceNm}.page(new Page<${entityName}>(page,pageLimit),new QueryWrapper<${entityName}>(entity));
        return ${resultClass }.${successMethod}(convert(response));
    }


    GetMapping(value ="view/{${idFiled}}")
    @ApiOperation("");
    @ApiImplicitParams({
        <#if "{idFiledType}"=="1">
            @ApiImplicitParam(paramType = "path", name = "${idFiled }", value = "主键", example = "1")
        <#else>
            @ApiImplicitParam(paramType = "path", name = "${idFiled }", value = "主键")
        </#if>
    })
    public ${resultClass }<${voName}> view( @PathVariable("${idFiled}") ${idType} ${idFiled}") {
        ${entityName} source = ${serviceNm}.getById(${idFiled});
        return  ${resultClass }.${successMethod}(convert(source));
    }

    @PostMapping(value="/add")
    @ApiOperation("")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "body", name = "request", value = "",dataType="${addDtoPath}")
    })
    public ${resultClass }<Object> add(@RequestBody ${addDTO} request) {
        ${entityName} entity = convert(request);
        int count = ${serviceNm}.insertSelective(entity);
        return count > 0?${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("添加数据失败，请稍后再试");
    }

    @PutMapping(value="/update")
    @ApiOperation("")
    @ApiImplicitParams({
        @ApiImplicitParam(paramType = "body", name = "request", value = "",dataType="${updateDTO}")
    })
    public ${resultClass }<Object> update(@RequestBody ${updateDTO} request) {
         ${entityName} entity = convert(request);
         boolean flag =  ${serviceNm}.updateByPrimaryKey(entity);
         return flag ? ${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("修改数据失败，请稍后再试");
    }

    <#if "${statucFlag}" =="1">
        @DeleteMapping(value="/update/status")
        @ApiOperation("")
        @ApiImplicitParams({
            @ApiImplicitParam(paramType = "body", name = "request", value = "",dataType="${updateStatusDTO}")
        })

        public ${resultClass}<Object> updateState(@RequestBody ${updateStatusDTO} request) {
            ${entityName} entity = convert(request);
            boolean flag =  ${serviceNm}.updateByPrimaryKey(entity);
            return flag ? ${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("修改数据失败，请稍后再试");
        }
    <#else>
        @DeleteMapping(value="/del/${idFiled}")
        @ApiOperation("")
       @ApiImplicitParams({
          <#if "{idFiledType}"=="1">
              @ApiImplicitParam(paramType = "path", name = "${idFiled }", value = "主键", example = "1")
          <#else>
              @ApiImplicitParam(paramType = "path", name = "${idFiled }", value = \"主键\")
          </#if>
       })
       public ${resultClass}<Object> delById(@PathVariable("${idFiled}") ${idType} ${idFiled}) {
            boolean flag =  ${serviceNm}.deleteById(${idFiled});
            return flag ? ${resultClass }.${successMethod}(Boolean.TRUE):${resultClass }.${errorMethod}("操作数据失败，请稍后再试");
        }
    </#if>

    private ${entityName} convert(${queryDTO} source) {
       return java.util.Optional.ofNullable(source).orElseGet(()->{
                ${entityName} target = new ${entityName}();
                BeanUtils.copyProperties(source, target);
                return target;
             });
    }

    private ${entityName} convert(${updateDTO} source) {
         return java.util.Optional.ofNullable(source).orElseGet(()->{
                    ${entityName} target = new ${entityName}();
                    BeanUtils.copyProperties(source, target);
                    return target;
                });
    }

     <#if "${statucFlag}" =="1">
             private ${entityName} convert(${updateStatusDTO} source) {
                 return java.util.Optional.ofNullable(source).orElseGet(()->{
                            ${entityName} target = new ${entityName}();
                            BeanUtils.copyProperties(source, target);
                            return target;
                        });
             }
     </#if>

       private ${entityName} convert(${addDTO} source) {
          return java.util.Optional.ofNullable(source).orElseGet(()->{
                     ${entityName} target = new ${entityName}();
                     BeanUtils.copyProperties(source, target);
                     return target;
                });
       }

     private ${voName} convert(${entityName} source) {
       return java.util.Optional.ofNullable(source).orElseGet(()->{
                  ${voName} target = new ${voName}();
                  BeanUtils.copyProperties(source, target);
                  return target;
             });
     }

     private List<${voName}> convert(List<${entityName}> sources) {
        return java.util.Optional.ofNullable(source).orElseGet(()->{
                 return sources.stream().map(source->{
                    return convert(source);
                  }).collect(Collectors.toList());
              });
     }

      private IPage<${voName}> convert(IPage<${entityName}> sources) {
             return java.util.Optional.ofNullable(source).orElseGet(()->{
                      IPage<${voName}> target = new com.baomidou.mybatisplus.extension.plugins.pagination.Page();
                      BeanUtils.copyProperties(source,target);
                      List<${voName}> voNames = convert(source.getRecords());
                      target.setRecords(voNames);

                     return target;
                   });
          }
}